package org.example.printexercise;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import java.util.ArrayList;
import java.util.List;

public class PracticeActivityDelay extends AppCompatActivity {
    private LinearLayout contentContainer;
    private NestedScrollView scrollView;
    private List<String> lines;
    private List<EditText> inputFields;
    private boolean[] lineCompletionStatus;
    private int currentFocusedLine = -1;
    private int screenHeight;
    private boolean firstLineChecked = false; // 新增：标记第一行是否至少检查过一次
    private boolean firstLineHasError = false; // 新增：标记第一行是否有错误

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_practice_delay);

        contentContainer = findViewById(R.id.contentContainer);
        scrollView = findViewById(R.id.scrollView);
        inputFields = new ArrayList<>();

        // 示例文本
        String sampleText = "This is the first line of text for practice.\n" +
                "We will test the display effect now.\n" +
                "This is the second line of text.\n" +
                "It is shorter than the previous one.\n" +
                "Third line demonstrates automatic wrapping.\n" +
                "Reading practice improves comprehension skills.\n" +
                "Fourth line contains basic sentence structure.\n" +
                "Fifth line shows varied text lengths.\n" +
                "Consistent practice yields better results.\n" +
                "Short exercises are effective for learning.\n" +
                "Tenth line marks the halfway point.\n" +
                "Focus on understanding each sentence fully.\n" +
                "Twelfth line continues the reading exercise.\n" +
                "Keep your reading pace steady.\n" +
                "Fourteenth line maintains proper word count.\n" +
                "Fifteenth line follows the format rules.\n" +
                "Nearly done with this practice set.\n" +
                "Seventeenth line keeps the pattern going.\n" +
                "Eighteenth line adheres to length limits.\n" +
                "Final two lines complete the exercise.\n" +
                "Twentieth line ends the sample text.";
        lines = new ArrayList<>();

        String[] splitLines = sampleText.split("\n");
        for (String line : splitLines) {
            lines.add(line);
        }

        lineCompletionStatus = new boolean[lines.size()];

        // 获取屏幕高度
        ViewTreeObserver observer = scrollView.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                scrollView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                screenHeight = scrollView.getHeight();
            }
        });

        setupTypingInterface();
    }

    private void setupTypingInterface() {
        for (int i = 0; i < lines.size(); i++) {
            // 添加原文本行
            TextView originalText = new TextView(this);
            originalText.setText(lines.get(i));
            originalText.setTextSize(18);
            originalText.setPadding(16, 16, 16, 8);
            originalText.setTextColor(Color.BLACK); // 设置原文本为黑色
            contentContainer.addView(originalText);

            // 添加用户输入行
            EditText userInput = new EditText(this);
            userInput.setHint(lines.get(i));
            userInput.setTextSize(18);
            userInput.setPadding(16, 8, 16, 16);
            userInput.setHintTextColor(0xFFCCCCCC); // 默认淡灰色提示文字
            userInput.setHorizontallyScrolling(false);
            userInput.setMaxLines(5);

            final int currentIndex = i;

            userInput.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
                        EditText currentField = (EditText) v;
                        String currentText = currentField.getText().toString();

                        if (currentText.isEmpty() && currentIndex > 0) {
                            EditText previousField = inputFields.get(currentIndex - 1);
                            String previousText = previousField.getText().toString();

                            userInput.post(() -> {
                                previousField.requestFocus();
                                previousField.setSelection(previousText.length());
                            });
                            return true;
                        }
                    }
                    return false;
                }
            });

            userInput.setOnFocusChangeListener((v, hasFocus) -> {
                if (hasFocus) {
                    if (currentFocusedLine != currentIndex) {
                        checkAllLines();
                        currentFocusedLine = currentIndex;
                    }

                    userInput.setSelection(userInput.getText().length());

                    // 检查是否需要自动滚动
                    checkAndScrollToPosition(userInput);

                    if (userInput.getText().toString().isEmpty()) {
                        lineCompletionStatus[currentIndex] = false;
                    }
                }
            });

            userInput.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    String expected = lines.get(currentIndex);
                    String actual = s.toString();

                    // 根据是否有输入内容改变提示文字颜色
                    if (actual.isEmpty()) {
                        userInput.setHintTextColor(0xFFCCCCCC); // 淡灰色
                    } else {
                        userInput.setHintTextColor(Color.BLACK); // 黑色
                    }

                    if (shouldAutoJump(currentIndex, actual, expected)) {
                        userInput.post(() -> {
                            lineCompletionStatus[currentIndex] = true;

                            if (currentIndex < inputFields.size() - 1) {
                                EditText nextField = inputFields.get(currentIndex + 1);
                                if (nextField.getText().toString().isEmpty()) {
                                    nextField.requestFocus();
                                }
                            }
                        });
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {}
            });

            contentContainer.addView(userInput);
            inputFields.add(userInput);
        }
    }

    /**
     * 检查并滚动到合适位置
     * @param focusedView 当前获得焦点的视图
     */
    private void checkAndScrollToPosition(View focusedView) {
        if (screenHeight == 0) return;

        int[] location = new int[2];
        focusedView.getLocationOnScreen(location);
        int viewTop = location[1];
        int viewBottom = viewTop + focusedView.getHeight();

        // 计算3/5和2/5位置
        int threeFifthPosition = screenHeight * 3 / 5;
        int twoFifthPosition = screenHeight * 2 / 5;

        // 如果视图底部超过3/5位置，则滚动到2/5位置
        if (viewBottom > threeFifthPosition) {
            int scrollToY = viewTop - twoFifthPosition;
            scrollView.smoothScrollTo(0, scrollToY);
        }
    }

    private void checkAllLines() {
        for (int i = 0; i < inputFields.size(); i++) {
            checkAndMarkLine(i);
        }
    }

    private boolean shouldAutoJump(int currentIndex, String actual, String expected) {
        if (actual.length() < expected.length()) {
            return false;
        }

        // 修改：对于第一行，如果至少检查过一次且有错误，则取消自动换行
        if (currentIndex == 0) {
            if (firstLineChecked && firstLineHasError) {
                return false; // 取消自动换行
            }
            return true; // 其他情况保持原有逻辑
        }

        if (!lineCompletionStatus[currentIndex]) {
            return true;
        }

        return false;
    }

    private void checkAndMarkLine(int lineIndex) {
        EditText targetInput = inputFields.get(lineIndex);
        String expected = lines.get(lineIndex);
        String actual = targetInput.getText().toString();

        if (!actual.isEmpty()) {
            // 新增：检查第一行是否有错误
            if (lineIndex == 0) {
                firstLineChecked = true; // 标记第一行至少检查过一次
                firstLineHasError = false; // 先重置错误状态

                // 检查是否有错误字符
                for (int j = 0; j < Math.min(expected.length(), actual.length()); j++) {
                    if (expected.charAt(j) != actual.charAt(j)) {
                        firstLineHasError = true;
                        break;
                    }
                }
                // 检查是否有多余字符
                if (actual.length() > expected.length()) {
                    firstLineHasError = true;
                }
            }

            SpannableStringBuilder spannable = new SpannableStringBuilder(actual);

            ForegroundColorSpan[] oldSpans = spannable.getSpans(0, spannable.length(), ForegroundColorSpan.class);
            for (ForegroundColorSpan span : oldSpans) {
                spannable.removeSpan(span);
            }

            for (int j = 0; j < Math.min(expected.length(), actual.length()); j++) {
                if (expected.charAt(j) != actual.charAt(j)) {
                    spannable.setSpan(
                            new ForegroundColorSpan(Color.RED),
                            j, j + 1,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    );
                }
            }

            if (actual.length() > expected.length()) {
                spannable.setSpan(
                        new ForegroundColorSpan(Color.RED),
                        expected.length(), actual.length(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                );
            }

            targetInput.setText(spannable);
            targetInput.setSelection(Math.min(targetInput.getSelectionStart(), spannable.length()));
        } else {
            targetInput.setText("");
            // 新增：如果第一行内容被清空，重置错误状态
            if (lineIndex == 0) {
                firstLineHasError = false;
            }
        }
    }
}